/*	Author		: Arga
 *	Created On	: Apr 25, 2011
 *	Description	: 
 */

package team8.paacdroid.activity;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import team8.paacdroid.R;
import team8.paacdroid.adapter.ItineraryAdapter;
import team8.paacdroid.bean.BusRide;
import team8.paacdroid.bean.Itinerary;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

public class ViewItineraryActivity extends ListActivity {
	// UI elements declarations
	private TextView tvTripName, tvTripDate;
	
	// Var declarations
	private ItineraryAdapter iAdapter;
	private String originString;
	private String destinationString;
	private ImageButton ibStar;
	private ListView lvItineraries;
	private static final int ADD_ID = Menu.FIRST+1;
	private static final int DELETE_ID = Menu.FIRST+3;
	
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		// Load the layout
		setContentView(R.layout.view_itinerary_activity);
		tvTripName = (TextView) findViewById(R.id.tvTripName);
		tvTripDate = (TextView) findViewById(R.id.tvTripDate);
		ibStar = (ImageButton) findViewById(R.id.ibStar);
		lvItineraries = (ListView) getListView();
		
		// Load the itineraries data
		@SuppressWarnings("unchecked")
		ArrayList<Itinerary> arrItineraries = (ArrayList<Itinerary>) getIntent().getSerializableExtra("Itineraries");
		
		if (arrItineraries != null && arrItineraries.size()>0) {
			// Load the original origin and destination string
			originString = arrItineraries.get(0).getOriginText();
			destinationString = arrItineraries.get(0).getDestinationText();
			
			// Check if this itinerary is a favorite, if it is, turn the star icon on.
			toggleStarIcon(checkFavoriteAlreadyExist());
			
			// Get the trip name (to be used as itinerary name) and display it.
			tvTripName.setText(arrItineraries.get(0).getTripName());
			
			// Get the trip date and display it
			DateFormat df = new SimpleDateFormat("M/d/yyyy");
			if (arrItineraries.get(0) != null && arrItineraries.get(0).getTripDate() != null) {
				tvTripDate.setText(df.format(arrItineraries.get(0).getTripDate()));
			}
			
			// Attach the list adapter to display the data
			iAdapter = new ItineraryAdapter(this, R.layout.itinerary_item, arrItineraries);
			setListAdapter(iAdapter);
		}
		
	}
	
	public void askMakeFavorite(View view) {
		// Check if this favorite is already in the favorites file
		if (!checkFavoriteAlreadyExist()) {
			// If it isn't, ask the user if he really wants to save this
			AlertDialog dialog = new AlertDialog.Builder(this).create();

			dialog.setMessage("Make this route a favorite?");
			dialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						// Save this route into a favorite
						saveFavorite(originString+"///"+destinationString);
						
						// Make the star shine
						toggleStarIcon(true);
					}
				});
			dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						// Do nothing
					}
				});
			dialog.show();
		}
	}
	
	private void saveFavorite(String savedString) {
		try {
			OutputStreamWriter out = new OutputStreamWriter(openFileOutput(getResources().getText(R.string.favorites_file_name).toString(), Context.MODE_APPEND));
			out.write(savedString+"\n");
			out.close();
		} catch (FileNotFoundException e) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("An error had occured: FileNotFoundException.");
			AlertDialog alert = builder.create();
			alert.show();
			Log.e(getString(R.string.app_name), "FileNotFoundException: " + e.getMessage());
			e.printStackTrace();
		} catch (NotFoundException e) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("An error had occured: NotFoundException.");
			AlertDialog alert = builder.create();
			alert.show();
			Log.e(getString(R.string.app_name), "NotFoundException: " + e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("An error had occured: IOException.");
			AlertDialog alert = builder.create();
			alert.show();
			Log.e(getString(R.string.app_name), "IOException: " + e.getMessage());
			e.printStackTrace();
		}
	}
	
	private void toggleStarIcon(boolean trueForOnFalseForOff) {
		if (trueForOnFalseForOff) {
			ibStar.setImageResource(R.drawable.star_on);
		} else {
			ibStar.setImageResource(R.drawable.star_off);
		}
	}
	
	private boolean isStarIconOn() {
		if (ibStar.getDrawable().equals(getResources().getDrawable(R.drawable.star_on))) {
			return true;
		} else {
			return false;
		}
	}
	
	private void displayAlert(Context ctx, String alertBoxTitle, String message, String closeButtonText) {
		new AlertDialog.Builder(this)
		.setTitle(alertBoxTitle)
		.setMessage(message)
		.setNeutralButton("Close", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dlg, int sumthin) {
			}
		})
		.show();
	}
	
	private boolean checkFavoriteAlreadyExist() {
	// Check if this route is already in the favorites list
	// Open the favorites file
		InputStream in;
		ArrayList<String> lines = new ArrayList<String>();
		try {
			in = openFileInput(getResources().getText(R.string.favorites_file_name).toString());
			if (in != null) {
				InputStreamReader tmp = new InputStreamReader(in);
				BufferedReader reader = new BufferedReader(tmp);
				String str;
				
				while ((str = reader.readLine()) != null) {
					lines.add(str);
				}
				
				in.close();
			}
		} catch (FileNotFoundException e) {
			Log.e(getString(R.string.app_name), "FileNotFoundException: " + e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("An error had occured: IOException.");
			AlertDialog alert = builder.create();
			alert.show();
			Log.e(getString(R.string.app_name), "IOException: " + e.getMessage());
			e.printStackTrace();
		}

		// Loop through the file to find this route
		boolean isThere = false;
		for (String line : lines) {
			if (line.equals(originString+"///"+destinationString)) {
				isThere = true;
				break;
			}
		}
		
		return isThere;
	}
	
	public void showItineraryDetails(View v) {
		// Create new intent
		Intent intentViewItineraryDetails = new Intent(this, ViewItineraryDetailsActivity.class);
		
		// Directly call the activity
		startActivity(intentViewItineraryDetails);
	}
}